package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlarmRuleMapper;
import com.zzyl.service.AlarmRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {
    @Autowired
    private AlarmRuleMapper alarmRuleMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AlarmRuleService alarmRuleService;

    @Scheduled(cron = "* * * * * ?")
    public void alertJob() {
        //1.查询所有的规则，如果没有规则，则结束这次校验
        List<AlertRule> alertRuleList = alarmRuleMapper.queryAlarm(null, null, null);
        if(CollUtil.isEmpty(alertRuleList)){
            return;
        }
        //2.如果有规则，则查询redis中所有设备缓存的数据（）json
        List<Object> values = stringRedisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        //3.判断json是否都为空，为空则结束这次校验
        if (CollUtil.isEmpty(values)){
            return;
        }
        //4.如果有数据则把json转换为vo对象
        List<DeviceDataVo> allDataList = new ArrayList<>();
        values.stream().forEach(val -> {
            String json = (String) val;//前往不要使用val.tostring()
            allDataList.addAll(JSONUtil.toList(json, DeviceDataVo.class));
        });
        //5.遍历每一天数据进行数据的校验
        allDataList.stream().forEach(vo -> {
            alarmRuleService.alertFilter(vo);
        });

    }
}
